from django.core.management.base import BaseCommand
from django.db import transaction
from battles.models import Battle
from django.utils import timezone


class Command(BaseCommand):
    help = '计算所有已完成战斗的精彩程度评分'

    def add_arguments(self, parser):
        parser.add_argument(
            '--force',
            action='store_true',
            help='强制重新计算所有战斗的精彩程度评分，包括已计算过的',
        )
        parser.add_argument(
            '--battle-id',
            type=int,
            help='仅计算指定ID的战斗',
        )

    def handle(self, *args, **options):
        force = options['force']
        battle_id = options.get('battle_id')
        
        # 获取需要计算的战斗
        if battle_id:
            battles = Battle.objects.filter(id=battle_id, status='finished')
            if not battles.exists():
                self.stdout.write(
                    self.style.ERROR(f'未找到ID为{battle_id}的已完成战斗')
                )
                return
        else:
            if force:
                battles = Battle.objects.filter(status='finished')
            else:
                battles = Battle.objects.filter(
                    status='finished',
                    excitement_calculated_at__isnull=True
                )
        
        total_battles = battles.count()
        if total_battles == 0:
            self.stdout.write(
                self.style.WARNING('没有需要计算精彩程度评分的战斗')
            )
            return
        
        self.stdout.write(f'开始计算 {total_battles} 场战斗的精彩程度评分...')
        
        updated_count = 0
        exciting_count = 0
        
        with transaction.atomic():
            for i, battle in enumerate(battles.iterator(), 1):
                try:
                    # 计算精彩程度评分
                    old_score = battle.excitement_score
                    old_exciting = battle.is_exciting
                    
                    battle.calculate_excitement_score()
                    battle.update_excitement_status()
                    battle.excitement_calculated_at = timezone.now()
                    battle.save(update_fields=[
                        'excitement_score', 
                        'is_exciting', 
                        'excitement_calculated_at'
                    ])
                    
                    updated_count += 1
                    if battle.is_exciting:
                        exciting_count += 1
                    
                    # 显示进度
                    if i % 100 == 0 or i == total_battles:
                        self.stdout.write(f'进度: {i}/{total_battles}')
                    
                    # 显示评分变化（如果是强制重新计算）
                    if force and (old_score != battle.excitement_score or old_exciting != battle.is_exciting):
                        self.stdout.write(
                            f'战斗 #{battle.id}: 评分 {old_score or 0:.1f} -> {battle.excitement_score:.1f}, '
                            f'精彩 {old_exciting} -> {battle.is_exciting}'
                        )
                
                except Exception as e:
                    self.stdout.write(
                        self.style.ERROR(f'计算战斗 #{battle.id} 时出错: {str(e)}')
                    )
        
        self.stdout.write(
            self.style.SUCCESS(
                f'完成！共更新 {updated_count} 场战斗，其中 {exciting_count} 场被标记为精彩战斗'
            )
        )
        
        # 显示统计信息
        total_exciting = Battle.objects.filter(is_exciting=True).count()
        total_finished = Battle.objects.filter(status='finished').count()
        
        if total_finished > 0:
            exciting_percentage = (total_exciting / total_finished) * 100
            self.stdout.write(
                f'当前精彩战斗统计: {total_exciting}/{total_finished} ({exciting_percentage:.1f}%)'
            )